<template>
  <div class="dashboard-container">
    <!-- 欢迎信息 -->
    <el-card class="welcome-card">
      <div class="welcome-info">
        <h2>欢迎使用高校教师绩效系统</h2>
        <p>当前用户：{{ userStore.user.realName || '未登录' }}</p>
        <p>角色：{{ roleMap[userStore.user.role] || '未知' }}</p>
        <p>今日日期：{{ currentDate }}</p>
      </div>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <!-- 管理员可见的用户统计卡片 -->
        <el-col :span="6" v-if="isAdmin">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <el-icon :size="40" color="#409EFF">
                <User />
              </el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ dashboardData.userStats?.totalUsers || 0 }}</div>
                <div class="stat-title">用户总数</div>
                <div class="stat-detail">教师: {{ dashboardData.userStats?.teacherCount || 0 }} | 管理员: {{ dashboardData.userStats?.adminCount || 0 }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 所有用户可见的科研项目卡片 -->
        <el-col :span="isAdmin ? 6 : 8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <el-icon :size="40" color="#67C23A">
                <Files />
              </el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ isAdmin ? dashboardData.researchStats?.totalProjects : userResearchStats.projects }}</div>
                <div class="stat-title">{{ isAdmin ? '科研项目' : '我的项目' }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 所有用户可见的论文卡片 -->
        <el-col :span="isAdmin ? 6 : 8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <el-icon :size="40" color="#E6A23C">
                <Document />
              </el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ isAdmin ? dashboardData.researchStats?.totalPapers : userResearchStats.papers }}</div>
                <div class="stat-title">{{ isAdmin ? '发表论文' : '我的论文' }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <!-- 所有用户可见的专利/奖项卡片 -->
        <el-col :span="isAdmin ? 6 : 8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-card-content">
              <el-icon :size="40" color="#F56C6C">
                <Trophy />
              </el-icon>
              <div class="stat-info">
                <div class="stat-value">{{ isAdmin ? (dashboardData.researchStats?.totalPatents + dashboardData.researchStats?.totalAwards) : (userResearchStats.patents + userResearchStats.awards) }}</div>
                <div class="stat-title">{{ isAdmin ? '专利/奖项' : '我的专利/奖项' }}</div>
                <div class="stat-detail">专利: {{ isAdmin ? dashboardData.researchStats?.totalPatents : userResearchStats.patents }} | 奖项: {{ isAdmin ? dashboardData.researchStats?.totalAwards : userResearchStats.awards }}</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <div class="chart-container">
      <el-row :gutter="20">
        <!-- 月度统计图表 -->
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>{{ isAdmin ? '月度统计' : '我的月度统计' }}</span>
              </div>
            </template>
            <v-chart class="chart" :option="monthlyOption" autoresize />
          </el-card>
        </el-col>

        <!-- 院系统计图表（仅管理员可见）/ 个人成果占比（教师可见） -->
        <el-col :span="12">
          <el-card shadow="hover" class="chart-card">
            <template #header>
              <div class="chart-header">
                <span>{{ isAdmin ? '院系统计' : '我的成果占比' }}</span>
              </div>
            </template>
            <v-chart class="chart" :option="isAdmin ? departmentOption : userTypeOption" autoresize />
          </el-card>
        </el-col>
      </el-row>

      <el-row :gutter="20" style="margin-top: 20px;">
        <!-- 最近活动 -->
        <el-col :span="12">
          <el-card shadow="hover" class="table-card">
            <template #header>
              <div class="chart-header">
                <span>{{ isAdmin ? '最近活动' : '我的最近活动' }}</span>
                <el-button type="primary" size="small" plain>查看全部</el-button>
              </div>
            </template>
            <el-table :data="isAdmin ? dashboardData.recentActivity : userRecentActivity" style="width: 100%" :max-height="400">
              <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
              <el-table-column prop="author" label="作者" width="100" v-if="isAdmin" />
              <el-table-column prop="type" label="类型" width="100">
                <template #default="scope">
                  <el-tag :type="getTypeTag(scope.row.type)">{{ getTypeText(scope.row.type) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" width="100">
                <template #default="scope">
                  <el-tag :type="getStatusTag(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="date" label="日期" width="120" />
            </el-table>
          </el-card>
        </el-col>

        <!-- 绩效排名（仅管理员可见） -->
        <el-col :span="12" v-if="isAdmin">
          <el-card shadow="hover" class="table-card">
            <template #header>
              <div class="chart-header">
                <span>绩效排名</span>
                <el-button type="primary" size="small" plain>查看全部</el-button>
              </div>
            </template>
            <el-table :data="dashboardData.performanceRanking" style="width: 100%" :max-height="400">
              <el-table-column prop="rank" label="排名" width="80">
                <template #default="scope">
                  <el-tag 
                    :type="scope.row.rank <= 3 ? ['', 'danger', 'warning', 'success'][scope.row.rank] : 'info'"
                    effect="plain"
                  >
                    {{ scope.row.rank }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="name" label="姓名" width="100" />
              <el-table-column prop="department" label="院系" min-width="150" show-overflow-tooltip />
              <el-table-column prop="score" label="绩效分" width="100">
                <template #default="scope">
                  <span class="score">{{ scope.row.score }}</span>
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useUserStore } from '../stores/user'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { BarChart, LineChart, PieChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import { 
  Files, 
  Document, 
  Trophy, 
  User
} from '@element-plus/icons-vue'
import axios from 'axios'

// 注册 ECharts 组件
use([
  CanvasRenderer,
  BarChart,
  LineChart,
  PieChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

const userStore = useUserStore()

// 判断是否为管理员
const isAdmin = computed(() => {
  return userStore.user.role === 'admin'
})

// 当前日期
const currentDate = new Date().toLocaleDateString('zh-CN', {
  year: 'numeric',
  month: 'long',
  day: 'numeric',
  weekday: 'long'
})

// 角色映射
const roleMap = {
  'admin': '管理员',
  'teacher': '教师',
  'reviewer': '审核员'
}

// 仪表盘数据
const dashboardData = ref({
  userStats: {},
  researchStats: {},
  monthlyStats: [],
  departmentStats: [],
  recentActivity: [],
  performanceRanking: []
})

// 教师个人研究统计数据
const userResearchStats = ref({
  projects: 0,
  papers: 0,
  patents: 0,
  awards: 0
})

// 教师个人绩效数据
const userRank = ref(0)
const userScore = ref(0)
const userDepartment = ref('')
const progressPercentage = ref(0)

// 计算进度条格式
const progressFormat = (percentage) => {
  return Math.round(percentage) + '分'
}

// 获取教师个人最近活动
const userRecentActivity = computed(() => {
  if (!dashboardData.value.recentActivity) return []
  return dashboardData.value.recentActivity.filter(
    item => item.author === userStore.user.realName
  )
})

// 获取类型标签样式
const getTypeTag = (type) => {
  const typeMap = {
    'project': 'primary',
    'paper': 'success',
    'patent': 'warning',
    'award': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取类型文本
const getTypeText = (type) => {
  const typeMap = {
    'project': '项目',
    'paper': '论文',
    'patent': '专利',
    'award': '奖项'
  }
  return typeMap[type] || type
}

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    'approved': 'success',
    'pending': 'warning',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'approved': '已审核',
    'pending': '待审核',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 月度统计图表配置
const monthlyOption = computed(() => {
  if (!dashboardData.value.monthlyStats || dashboardData.value.monthlyStats.length === 0) {
    return {}
  }

  // 反转数组以便按时间顺序显示
  const data = [...dashboardData.value.monthlyStats].reverse()
  
  const months = data.map(item => item.month)
  const projects = data.map(item => item.projects)
  const papers = data.map(item => item.papers)
  const patents = data.map(item => item.patents)
  const awards = data.map(item => item.awards)
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['项目', '论文', '专利', '奖项'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      minInterval: 1
    },
    series: [
      {
        name: '项目',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: projects,
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '论文',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: papers,
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '专利',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: patents,
        itemStyle: {
          color: '#E6A23C'
        }
      },
      {
        name: '奖项',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: awards,
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
})

// 院系统计图表配置
const departmentOption = computed(() => {
  if (!dashboardData.value.departmentStats || dashboardData.value.departmentStats.length === 0) {
    return {}
  }
  
  const departments = dashboardData.value.departmentStats.map(item => item.department)
  
  return {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['项目', '论文', '专利', '奖项'],
      bottom: 0
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '10%',
      top: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      minInterval: 1
    },
    yAxis: {
      type: 'category',
      data: departments,
      axisLabel: {
        interval: 0
      }
    },
    series: [
      {
        name: '项目',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: dashboardData.value.departmentStats.map(item => item.projects),
        itemStyle: {
          color: '#409EFF'
        }
      },
      {
        name: '论文',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: dashboardData.value.departmentStats.map(item => item.papers),
        itemStyle: {
          color: '#67C23A'
        }
      },
      {
        name: '专利',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: dashboardData.value.departmentStats.map(item => item.patents),
        itemStyle: {
          color: '#E6A23C'
        }
      },
      {
        name: '奖项',
        type: 'bar',
        stack: 'total',
        emphasis: {
          focus: 'series'
        },
        data: dashboardData.value.departmentStats.map(item => item.awards),
        itemStyle: {
          color: '#F56C6C'
        }
      }
    ]
  }
})

// 教师个人成果占比图表
const userTypeOption = computed(() => {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 10,
      data: ['项目', '论文', '专利', '奖项']
    },
    series: [
      {
        name: '成果类型',
        type: 'pie',
        radius: ['50%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: userResearchStats.value.projects, name: '项目', itemStyle: { color: '#409EFF' } },
          { value: userResearchStats.value.papers, name: '论文', itemStyle: { color: '#67C23A' } },
          { value: userResearchStats.value.patents, name: '专利', itemStyle: { color: '#E6A23C' } },
          { value: userResearchStats.value.awards, name: '奖项', itemStyle: { color: '#F56C6C' } }
        ]
      }
    ]
  }
})

// 获取首页数据
const fetchDashboardData = async () => {
  try {
    if (isAdmin.value) {
      // 管理员使用原有接口
      const response = await axios.get('http://localhost:8081/api/home/data')
      if (response.data.code === 200) {
        dashboardData.value = response.data.data.data
      }
    } else {
      // 教师使用新接口
      // 获取当前教师ID
      const teacherId = await fetchCurrentTeacherId()
      if (teacherId) {
        const response = await axios.get(`http://localhost:8081/api/home/teacher-data?tid=${teacherId}`)
        if (response.data.code === 200) {
          // 处理教师数据
          const teacherData = response.data.data
          
          // 更新教师研究统计数据
          userResearchStats.value = {
            projects: teacherData.projectList?.length || 0,
            papers: teacherData.paperList?.length || 0,
            patents: teacherData.patentList?.length || 0,
            awards: teacherData.awardList?.length || 0
          }
          
          // 构建最近活动数据
          const recentActivity = []
          
          // 添加项目到最近活动
          teacherData.projectList?.forEach(project => {
            recentActivity.push({
              title: project.name,
              author: userStore.user.realName,
              type: 'project',
              status: project.status,
              date: project.startDate
            })
          })
          
          // 添加论文到最近活动
          teacherData.paperList?.forEach(paper => {
            recentActivity.push({
              title: paper.title,
              author: userStore.user.realName,
              type: 'paper',
              status: paper.status,
              date: paper.publishDate
            })
          })
          
          // 添加专利到最近活动
          teacherData.patentList?.forEach(patent => {
            recentActivity.push({
              title: patent.name,
              author: userStore.user.realName,
              type: 'patent',
              status: patent.status,
              date: patent.authorizationDate
            })
          })
          
          // 添加奖项到最近活动
          teacherData.awardList?.forEach(award => {
            recentActivity.push({
              title: award.name,
              author: userStore.user.realName,
              type: 'award',
              status: award.status,
              date: award.awardDate
            })
          })
          
          // 按日期排序，最新的在前
          recentActivity.sort((a, b) => new Date(b.date) - new Date(a.date))
          
          // 更新仪表盘数据
          dashboardData.value = {
            ...dashboardData.value,
            recentActivity: recentActivity
          }
          
          // 更新月度统计数据（示例：按月份分组统计）
          const monthlyStats = generateMonthlyStats(teacherData)
          dashboardData.value.monthlyStats = monthlyStats
        }
      }
    }
    
    // 如果是教师，计算个人数据
    if (!isAdmin.value) {
      calculateUserData()
    }
  } catch (error) {
    console.error('获取首页数据失败:', error)
  }
}

// 获取当前教师ID
const fetchCurrentTeacherId = async () => {
  try {
    // 从localStorage获取user并解析JSON
    let userId = userStore.userId
    if (!userId) {
      const userStr = localStorage.getItem('user')
      if (userStr) {
        try {
          const userObj = JSON.parse(userStr)
          userId = userObj.id
        } catch (e) {
          console.error('解析用户信息错误:', e)
        }
      }
    }
    
    if (userId) {
      const response = await axios.get(`http://localhost:8081/api/teacher/getByUserId?userId=${userId}`)
      if (response.data.code === 200 && response.data.data) {
        // 从返回的数据中获取教师ID
        return response.data.data.teacher.id
      }
    } else {
      console.error('未找到用户ID')
    }
  } catch (error) {
    console.error('获取当前教师ID错误:', error)
  }
  return 2  // 默认返回ID为2的教师（根据您的示例）
}

// 生成月度统计数据
const generateMonthlyStats = (teacherData) => {
  // 创建月份映射
  const monthMap = {}
  
  // 处理项目数据
  teacherData.projectList?.forEach(project => {
    const date = new Date(project.startDate)
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    
    if (!monthMap[monthKey]) {
      monthMap[monthKey] = { month: monthKey, projects: 0, papers: 0, patents: 0, awards: 0 }
    }
    
    monthMap[monthKey].projects++
  })
  
  // 处理论文数据
  teacherData.paperList?.forEach(paper => {
    const date = new Date(paper.publishDate)
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    
    if (!monthMap[monthKey]) {
      monthMap[monthKey] = { month: monthKey, projects: 0, papers: 0, patents: 0, awards: 0 }
    }
    
    monthMap[monthKey].papers++
  })
  
  // 处理专利数据
  teacherData.patentList?.forEach(patent => {
    const date = new Date(patent.authorizationDate)
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    
    if (!monthMap[monthKey]) {
      monthMap[monthKey] = { month: monthKey, projects: 0, papers: 0, patents: 0, awards: 0 }
    }
    
    monthMap[monthKey].patents++
  })
  
  // 处理奖项数据
  teacherData.awardList?.forEach(award => {
    const date = new Date(award.awardDate)
    const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    
    if (!monthMap[monthKey]) {
      monthMap[monthKey] = { month: monthKey, projects: 0, papers: 0, patents: 0, awards: 0 }
    }
    
    monthMap[monthKey].awards++
  })
  
  // 转换为数组并按月份排序
  return Object.values(monthMap).sort((a, b) => a.month.localeCompare(b.month))
}

// 计算教师个人数据
const calculateUserData = () => {
  const userName = userStore.user.realName
  
  // 计算个人研究统计
  userResearchStats.value = {
    projects: 0,
    papers: 0,
    patents: 0,
    awards: 0
  }
  
  // 从最近活动中统计个人成果
  if (dashboardData.value.recentActivity) {
    dashboardData.value.recentActivity.forEach(item => {
      if (item.author === userName && item.status !== 'rejected') {
        switch (item.type) {
          case 'project':
            userResearchStats.value.projects++
            break
          case 'paper':
            userResearchStats.value.papers++
            break
          case 'patent':
            userResearchStats.value.patents++
            break
          case 'award':
            userResearchStats.value.awards++
            break
        }
      }
    })
  }
  
  // 获取个人绩效排名信息
  if (dashboardData.value.performanceRanking) {
    const userRanking = dashboardData.value.performanceRanking.find(item => item.name === userName)
    if (userRanking) {
      userRank.value = userRanking.rank
      userScore.value = userRanking.score
      userDepartment.value = userRanking.department
      
      // 计算与上一名的差距
      if (userRank.value > 1) {
        const higherRank = dashboardData.value.performanceRanking.find(item => item.rank === userRank.value - 1)
        if (higherRank) {
          const scoreDiff = higherRank.score - userScore.value
          progressPercentage.value = scoreDiff
        }
      } else {
        progressPercentage.value = 0
      }
    }
  }
}

// 根据用户角色调整显示内容
onMounted(() => {
  fetchDashboardData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
  background: linear-gradient(to right, #1e88e5, #4fc3f7);
  color: white;
}

.welcome-info {
  padding: 10px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  display: flex;
  align-items: center;
}

.stat-card-content {
  display: flex;
  align-items: center;
  justify-content: space-around;
}

.stat-info {
  margin-left: 15px;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 5px;
}

.stat-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 5px;
}

.stat-detail {
  font-size: 12px;
  color: #909399;
}

.chart-container {
  margin-top: 20px;
}

.chart-card, .table-card {
  margin-bottom: 20px;
}

.chart {
  height: 350px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.score {
  font-weight: bold;
  color: #F56C6C;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .chart {
    height: 250px;
  }
  
  .performance-item {
    width: 100%;
  }
}
</style>
